package com.justnow.offer;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author justnow
 * Created on 2020-10-06
 * Description
 */
public class Demo02 {
    private static Queue<Integer> queue = new LinkedList<>();
    private static int size = 10;
    public static void main(String[] args) {
        Thread producer = new Thread(() -> {
                int i = 1;
                while (true) {
                    synchronized (queue) {
                    if (queue.size() >= size) {
                        try {
                            System.out.println("当前库存量: " + queue.size() + "。不能生产了！");
                            i = 0;
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        queue.add(i);
                        System.out.println("生产者生成" + i);
                        System.out.println("当前库存量: " + queue.size());
                        queue.notifyAll();
                    }
                    i++;
                }
            }
        });

        Thread consumer = new Thread(() -> {
                while (true) {
                    synchronized (queue) {
                    if (queue.size() <= 0) {
                        try {
                            System.out.println("当前库存量: " + queue.size() + "。不能再消费了");
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        int number = queue.remove();
                        System.out.println("消费者消费：" + number);
                        System.out.println("当前库存量: " + queue.size());
                        queue.notifyAll();
                    }
                }
            }
        });
        producer.start();
        consumer.start();
    }


}
